import 'dart:io';

import 'package:camera/camera.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';

import '../../bean/Media.dart';
import '../../network/Loading.dart';
import '../../utils/date_time_utils.dart';
import '../../utils/permission_utils.dart';
import '../../utils/video_compress_utils.dart';
import '../ImagesGridviewWidget.dart';
import 'camera.dart';
import 'media.dart';

export '../../bean/Media.dart';

class CameraUtils {
  // 私有构造函数
  CameraUtils._internal() {
    cameras = [];
  }

  // 保存单例
  static final CameraUtils _instance = CameraUtils._internal();

  // 工厂构造函数
  factory CameraUtils() {
    return _instance;
  }

  late List<CameraDescription> cameras;

  // 拍摄照片
  Future<Media?> takePicture({String? dirName, int maxRecordDuration = 60}) async {
    // 获取 相机权限
    if (await PermissionUtils().getCamera()) {
      // 获取 麦克风权限
      if (await PermissionUtils().getMicrophone()) {
        // 使用相机
        cameras = await availableCameras();
        MediaModel? mod = await Get.to(() => CameraPage(
              dirName: dirName,
              maxRecordDuration: maxRecordDuration,
            ));
        Loading.show();

        if (mod != null) {
          Media media = Media();
          media.name = mod.file?.name;
          media.path = mod.file?.path;
          media.thumbPath = mod.file?.path;
          media.dateTime = DateTimeUtils.getNow();
          if (mod.isImage) {
            media.galleryMode = GalleryMode.image;
          } else {
            media.galleryMode = GalleryMode.video;
            File thumb = await VideoCompressUtils().getFileThumbnail(mod.file?.path ?? "");
            media.thumbPath = thumb.path;
          }
          Loading.dismiss();
          return media;
        }
      }
    }
    Loading.dismiss();
    return null;
  }
}
